package world.criver.h50529.controller;

import javafx.application.Platform;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import world.criver.h50529.data.daControllers;
import world.criver.h50529.data.daData;
import world.criver.h50529.data.daFun;
import world.criver.h50529.function.funFiles;
import world.criver.h50529.function.funMessageFormat;
import world.criver.h50529.module.moEvent;
import world.criver.h50529.module.moGroup;
import world.criver.h50529.module.moGroupEvent;

import java.net.InetAddress;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

import static world.criver.h50529.data.daData.events;

public class conPage5AddGroup implements Initializable {
    public VBox list;
    public Label label_1;
    public TextField name;
    public Label name_tip;
    public VBox tcp_udp_list;
    public TextField ip1;
    public TextField ip2;
    public TextField ip3;
    public TextField ip4;
    public TextField port;
    public VBox list_item;
    public Label tip;
    public TextField command;
    public ComboBox<String> commandType;

    private moGroup group;
    private boolean is_update=false;

    public void onAdd() {
        createEvent(null,-1);
    }

    public void onSave() {
        String name = this.name.getText();
        if (name.isEmpty()) {
            tip.setText("请输入名称");
            return;
        }
        if (name.length() > 20) {
            tip.setText("名称长度不得超过20字符");
            return;
        }
        if (port.getText().isEmpty()) {
            tip.setText("请输入接收端端口号");
            return;
        }
        if(command.getText().isEmpty()){
            tip.setText("请输入触发转发的数据");
            return;
        }
        group.setIp(ip1.getText() + "." + ip2.getText() + "." + ip3.getText() + "." + ip4.getText());
        group.setPort(Integer.parseInt(port.getText()));
        group.setCommand(command.getText());
        group.setCommandType(commandType.getSelectionModel().getSelectedItem());
        ArrayList<moGroupEvent> items=new ArrayList<>();
        for(int i=0;i<list_item.getChildren().size();i++){
            HBox hb=(HBox)list_item.getChildren().get(i);
            ComboBox<String> cb=(ComboBox)hb.getChildren().get(0);
            String t=((TextField)hb.getChildren().get(1)).getText();
            items.add(new moGroupEvent(cb.getSelectionModel().getSelectedItem(),Double.parseDouble("0"+t)));
        }
        group.setItems(items);
        for (moGroup mg : daData.groups) {
            if (mg.getName().equals(group.getName())) {
                daFun.funGroup.updateName(group.getName(), name);
                group.setName(name);
                tip.setText("保存成功");
                daControllers.master.onMenuItem5();
                new funFiles().saveTransmit();
                return;
            }
        }
        group.setName(name);
        tip.setText("保存成功");
        daData.groups.add(group);
        daControllers.master.onMenuItem5();
        new funFiles().saveTransmit();
    }
    public void onShow(moGroup group){
        try {
            this.group = null;
            tip.setText("");
            is_update = group != null;
            if (group == null) this.group = new moGroup();
            else this.group = group;
            name.setText(this.group.getName());
            String[] ips = InetAddress.getLocalHost().getHostAddress().split("\\.");
            ip1.setText("255");
            ip2.setText("255");
            ip3.setText("255");
            ip4.setText("255");
            ip1.setEditable(false);
            ip2.setEditable(false);
            ip3.setEditable(false);
            ip4.setEditable(false);
            port.setText(this.group.getPort() + "");
            command.setText(this.group.getCommand());
            commandType.getItems().clear();
            commandType.getItems().add("hex");
            commandType.getItems().add("str");
            commandType.getSelectionModel().select(this.group.getCommandType());
            list_item.getChildren().clear();
            for (moGroupEvent event:this.group.getItems()) createEvent(event.getName(), event.getWait());
            if(list_item.getChildren().isEmpty())createEvent(null,-1);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    private void createEvent(String eventName,double wait){
        HBox hb=new HBox();
        hb.getStyleClass().add("HBox");

        ComboBox<String> b=new ComboBox<>();
        b.setStyle("-fx-pref-width: 241;-fx-font-size: 10;-fx-pref-height: 25");
        for(moEvent ev:daData.events)b.getItems().add(ev.getName());
        if(eventName==null || eventName.isEmpty())b.getSelectionModel().select(0);
        else b.getSelectionModel().select(eventName);
        hb.getChildren().add(b);

        TextField c=new TextField(wait<0?"":(wait+""));
        c.setPromptText("延时(s)");
        c.setStyle("-fx-pref-width: 60");
        hb.getChildren().add(c);

        Button delete=new Button("X");
        delete.setStyle("-fx-pref-width: 26");
        hb.getChildren().add(delete);

        list_item.getChildren().add(hb);

        c.setTextFormatter(new TextFormatter<String>(e->{
            String n=e.getControlNewText();
            try{
                Double.parseDouble("0"+n);
                return e;
            }catch (Exception ee){
                return null;
            }
        }));
        delete.setOnAction(e->{
            list_item.getChildren().remove(hb);
        });
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Platform.runLater(()->{
            name.setTextFormatter(new TextFormatter<String>(e->{
                name_tip.setText("");
                String n=e.getControlNewText();
                if(n.isEmpty())return e;
                if(n.matches("^[\\p{L}\\p{N}]*$") && n.length()<=64){
                    if(!is_update){
                        for(moGroup mo: daData.groups)if(mo.getName().equals(n))name_tip.setText("名称已存在");
                    }
                    return e;
                }
                return null;
            }));
//            setTextFieldOnlyNumber(ip1,255);
//            setTextFieldOnlyNumber(ip2,255);
//            setTextFieldOnlyNumber(ip3,255);
//            setTextFieldOnlyNumber(ip4,255);
//            setTextFieldOnlyNumber(port,65535);
        });
    }
    private void setTextFieldOnlyNumber(TextField tf,int max){
        tf.setTextFormatter(new TextFormatter<Integer>(e->{
            String a=e.getControlNewText();
            if(a.isEmpty())return e;//56-4a-65-98-54-65
            if(a.contains(".")||a.contains(":")){
                String[] ips=a.split(":")[0].split("\\.");//192.168.0.192:12345
                String port=a.contains(":")?a.split(":")[1]:"";
                if(ips.length>0&&tf!=ip1&&ips[0].matches("\\d+"))if(Integer.parseInt(ips[0])<=255)ip1.setText(ips[0]);
                if(ips.length>1&&tf!=ip2&&ips[1].matches("\\d+"))if(Integer.parseInt(ips[1])<=255)ip2.setText(ips[1]);
                if(ips.length>2&&tf!=ip3&&ips[2].matches("\\d+"))if(Integer.parseInt(ips[2])<=255)ip3.setText(ips[2]);
                if(ips.length>3&&tf!=ip4&&ips[3].matches("\\d+"))if(Integer.parseInt(ips[3])<=255)ip4.setText(ips[3]);
                if(tf!=this.port&&port.matches("\\d+"))if(Integer.parseInt(port)<=65535)this.port.setText(port);
                if(tf==ip1&&ips.length>0&&ips[0].matches("\\d+")){if(Integer.parseInt(ips[0])<=255)e.setText(ips[0]);else return null;}
                else if(tf==ip2&&ips.length>1&&ips[1].matches("\\d+")){if(Integer.parseInt(ips[1])<=255)e.setText(ips[1]);else return null;}
                else if(tf==ip3&&ips.length>2&&ips[2].matches("\\d+")){if(Integer.parseInt(ips[2])<=255)e.setText(ips[2]);else return null;}
                else if(tf==ip4&&ips.length>3&&ips[3].matches("\\d+")){if(Integer.parseInt(ips[3])<=255)e.setText(ips[3]);else return null;}
                else if(tf==this.port&&port.matches("\\d+")){if(Integer.parseInt(port)<=65536)e.setText(port);else return null;}
                else return null;
                return e;
            }
            if(a.matches("\\d+")){
                if(!e.getControlNewText().isEmpty())if(Integer.parseInt(e.getControlNewText())>max)return null;
                return e;
            }
            return null;
        }));
    }
}
